import { HttpException, HttpStatus, Injectable } from "@nestjs/common";
import * as nodemailer from "nodemailer"
import SMTPTransport from "nodemailer/lib/smtp-transport";
import Mail from "nodemailer/lib/mailer";
import { Observable, concatMap, map } from "rxjs";
import { ConfigService } from "@nestjs/config";

export type MailOptions = Mail.Options


@Injectable()
export class SyncEmailService {
  constructor(
    private readonly configService: ConfigService
  ) {}
  getTransporter(): nodemailer.Transporter {
    const options: SMTPTransport.Options = {
      host: this.configService.get("EMAIL_STMP_HOST"),
      port: +this.configService.get("EMAIL_STMP_PORT"),
      secure: true, // use SSL
      auth: {
        // 发件人邮箱账号
        user: this.configService.get("EMAIL_STMP_USER"),
        //发件人邮箱的授权码 这里可以通过qq邮箱获取 并且不唯一
        pass: this.configService.get("EMAIL_STMP_PASS"),
      },
    }
    return nodemailer.createTransport(options)
  }
  send(mail: MailOptions): Observable<{status: boolean, message: string}> {
    return new Observable(observer => {
      const transporter = this.getTransporter()
      const extendMail: MailOptions = {
        from: this.configService.get("EMAIL_STMP_NICK"),
        ...mail
      }
      transporter.sendMail(extendMail, function(error, info) {
        if (error) {
          observer.error(new HttpException(`Send mail failed. ${error?.message}`, HttpStatus.BAD_REQUEST))
        } else {
          observer.next({status: true, message: info?.response})
        }
        transporter.close()
        observer.complete()
      })
    })
    
  }

  reportToEmail(type: string, content: string) {
    const code: string = Math.random().toString().substring(2, 8)
    const mail: MailOptions = {
      to: "979358990@qq.com",
      subject: `vpuber ${type}`,
      html: content,
    }
    return this.send(mail)
  }
}